package com.edu.whty.interceptor;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.edu.whty.common.tools.HttpClient;
import com.edu.whty.common.tools.IpUtils;
import com.edu.whty.common.tools.SensorsAnalyticsUtils;
import com.edu.whty.entity.cloud.CloudId;
import com.edu.whty.entity.cloud.DeleteCloudReq;
import com.edu.whty.entity.cloud.TbCourseUser;
import com.edu.whty.entity.cloud.UserResRequest2;
import com.edu.whty.service.CourseService;
import com.sensorsdata.analytics.javasdk.SensorsAnalytics;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Component
public class BigDataInterceptor implements HandlerInterceptor {
	Logger LOGGER = LoggerFactory.getLogger(BigDataInterceptor.class);

    @Autowired
    private CourseService courseService;

    
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return true;
    }


    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String servletPath = request.getServletPath();
        LOGGER.info("埋点请求URI：{}", servletPath);
        if("/cloud/saveCloudRes".equals(servletPath)) {
            String type = request.getParameter("type");
            Map map = (Map) request.getAttribute("map");
            List<UserResRequest2> userResList = (List<UserResRequest2>) map.get("userReslist");
            String platformCode = userResList.get(0).getPlatformCode();
            String loginPlatformCode = userResList.get(0).getLoginPlatformCode();
            List array = (List) map.get("array");

            //加入备课积分埋点
            for (UserResRequest2 userRes : userResList) {
                Map<String, Object> properties = new HashMap<>();
                properties.put("buryType", "1");
                properties.put("object_id", userRes.getResId());
                properties.put("platform_code", loginPlatformCode);
                properties.put("sourceColumn", "1");
                properties.put("terminalType", "api");
                properties.put("object_id", userRes.getResId());
                properties.put("object_type", "resource");
                pushData("CollectResource", userRes.getUserId(), properties);
            }

            if ("1".equals(type)) {
                if("640000".equals(loginPlatformCode)){
                    for (UserResRequest2 res : userResList) {
                        Map<String, Object> properties = new HashMap<>();
                        if (null != res) {
                            properties.put("xxmc", res.getOrgName());
                            properties.put("xk", res.getSubjectName());
                            properties.put("xd", res.getPeriodName());
                            properties.put("ls", res.getUserName());
                            properties.put("bkrq", new Date());
                            properties.put("xxbm", res.getOrgId());
                            properties.put("lsbm",res.getUserId() );
                            properties.put("nj", res.getGradeId());
                            properties.put("kjmc", res.getTitle());
                            properties.put("ywbm", "JXYY_BKJL");
                        }
                        properties.put("$time", new Date());
                        properties.put("object_id", res.getResId());
                        properties.put("object_type", "PPTResource");
                        pushData("CreatePPTResource", res.getUserId(), properties);
                    }
                }else {
                    for (UserResRequest2 userRes : userResList) {
                        Map<String, Object> properties = getCommonParam(userRes);
                        properties.put("object_id", userRes.getResId());
                        properties.put("object_type", "PPTResource");
                        pushData("CreatePPTResource", userRes.getUserId(), properties);
                    }
                }

            } else if ("2".equals(type)) {
                for (UserResRequest2 userRes : userResList) {
                    Map<String, Object> properties = getCommonParam(userRes);
                    properties.put("object_id", userRes.getResId());
                    properties.put("object_type", "InteractResource");
                    pushData("CreateInteractResource", userRes.getUserId(), properties);
                }
            } else if ("3".equals(type)) {
                for (UserResRequest2 userRes : userResList) {
                    Map<String, Object> properties = getCommonParam(userRes);
                    properties.put("object_id", userRes.getResId());
                    properties.put("object_type", "resource");
                    pushData("UploadResource", userRes.getUserId(), properties);
                }
            } else if ("4".equals(type)) {
                for (UserResRequest2 userRes : userResList) {
                    Map<String, Object> properties = getCommonParam(userRes);
                    properties.put("object_id", userRes.getResId());
                    properties.put("object_type", "resource");
                    pushData("UploadResourcePackage", userRes.getUserId(), properties);
                }
            }else if ("5".equals(type)) {
                for (UserResRequest2 userRes : userResList) {
                    Map<String, Object> properties = getCommonParam(userRes);
                    properties.put("object_id", userRes.getResId());
                    properties.put("object_type", "resource");
                    pushData("RecommendResourceAdd", userRes.getUserId(), properties);
                }
            }else if ("6".equals(type)) {
                for (UserResRequest2 userRes : userResList) {
                    Map<String, Object> properties = getCommonParam(userRes);
                    properties.put("object_id", userRes.getResId());
                    properties.put("object_type", "resource");
                    pushData("SchoolResourceAdd", userRes.getUserId(), properties);
                }
            }else if ("7".equals(type)) {
                for (UserResRequest2 userRes : userResList) {
                    Map<String, Object> properties = getCommonParam(userRes);
                    properties.put("object_id", userRes.getResId());
                    properties.put("object_type", "resource");
                    pushData("CloudResourceAdd", userRes.getUserId(), properties);
                }
            }else if ("8".equals(type)) {
                for (UserResRequest2 userRes : userResList) {
                    Map<String, Object> properties = getCommonParam(userRes);
                    properties.put("object_id", userRes.getResId());
                    properties.put("object_type", "resource");
                    pushData("YsyykResourceAdd", userRes.getUserId(), properties);
                }
            }else if ("9".equals(type)) {
                for (UserResRequest2 userRes : userResList) {
                    Map<String, Object> properties = getCommonParam(userRes);
                    properties.put("object_id", userRes.getResId());
                    properties.put("object_type", "resource");
                    pushData("YunResourceAdd", userRes.getUserId(), properties);
                }
            }else if ("10".equals(type)) {
                for (UserResRequest2 userRes : userResList) {
                    Map<String, Object> properties = getCommonParam(userRes);
                    properties.put("object_id", userRes.getResId());
                    properties.put("object_type", "resource");
                    pushData("FanglveAdd", userRes.getUserId(), properties);
                }
            }else if ("11".equals(type)) {
                for (UserResRequest2 userRes : userResList) {
                    Map<String, Object> properties = getCommonParam(userRes);
                    properties.put("object_id", userRes.getResId());
                    properties.put("object_type", "resource");
                    pushData("NetpadResourceAdd", userRes.getUserId(), properties);
                }
            }else if ("12".equals(type)) {
                for (UserResRequest2 userRes : userResList) {
                    Map<String, Object> properties = getCommonParam(userRes);
                    properties.put("object_id", userRes.getResId());
                    properties.put("object_type", "resource");
                    pushData("LangyingAdd", userRes.getUserId(), properties);
                }
            }else if ("13".equals(type)) {
                for (UserResRequest2 userRes : userResList) {
                    Map<String, Object> properties = getCommonParam(userRes);
                    properties.put("object_id", userRes.getResId());
                    properties.put("object_type", "resource");
                    pushData("HaimaAdd", userRes.getUserId(), properties);
                }
            }else if ("14".equals(type)) {
                for (UserResRequest2 userRes : userResList) {
                    Map<String, Object> properties = getCommonParam(userRes);
                    properties.put("object_id", userRes.getResId());
                    properties.put("object_type", "resource");
                    pushData("XuekewangAdd", userRes.getUserId(), properties);
                }
            }else if ("15".equals(type)) {
                for (UserResRequest2 userRes : userResList) {
                    Map<String, Object> properties = getCommonParam(userRes);
                    properties.put("object_id", userRes.getResId());
                    properties.put("object_type", "resource");
                    pushData("NationResourceAdd", userRes.getUserId(), properties);
                }
            }

            for (int i = 0; i < array.size(); i++) {
                JSONObject finalJson = new JSONObject();
                String json = (String) array.get(i);
                LOGGER.info("参数1：" + json);
                finalJson.put("userSessionId", "jxzsRes");
                finalJson.put("platformCode", StringUtils.isEmpty(platformCode) ? platformCode : loginPlatformCode);
                finalJson.put("loginPlatformCode", loginPlatformCode);
                finalJson.put("topic", "jxzsRes");
                finalJson.put("data", json);
                LOGGER.info("参数2：" + finalJson);
                String upSyncUrl = "http://kcapi.huijiaoyun.com/res-course/logMessage/saveKafka";
                String jsonStr = finalJson.toJSONString();
                LOGGER.info("参数3：" + jsonStr);
                String textbookResponse = HttpClient.doJSONPostMethod(upSyncUrl, jsonStr);
                LOGGER.info("Response==="+textbookResponse);
            }

        }else if("/cloud/deleteCloud".equals(servletPath)){
            DeleteCloudReq deleteCloudReq = (DeleteCloudReq)request.getAttribute("deleteCloudReq");

                for (CloudId cloud : deleteCloudReq.getList()) {
                    TbCourseUser tbCourseUser = courseService.getUserByCourseId(cloud.getCourseId());
                    com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
                    com.alibaba.fastjson.JSONObject data = new com.alibaba.fastjson.JSONObject();
                    JSONObject finalJson = new JSONObject();
                    data.put("optType","2");
                    data.put("source","rrtpc");
                    data.put("sourceId",cloud.getCourseId());
                    data.put("userId",tbCourseUser.getCourseUserid());
                    data.put("loginPlatformCode",tbCourseUser.getLoginPlatformCode());
                    json.put("classRoomId",data.toJSONString());
                    json.put("type","12");
                    json.put("createTime",System.currentTimeMillis());
                    json.put("userId",deleteCloudReq.getUserId());
                    json.put("loginPlatformCode",tbCourseUser.getLoginPlatformCode());
                    json.put("platformCode","http://rrtbk.rrt-pc.svc.cluster.local:8080/rrtbk-api/cloud/updateUsrRes");
                    finalJson.put("userSessionId", "jxzsRes");
                    finalJson.put("platformCode", StringUtils.isEmpty(tbCourseUser.getPlatformCode()) ? tbCourseUser.getPlatformCode() : tbCourseUser.getLoginPlatformCode());
                    finalJson.put("loginPlatformCode", tbCourseUser.getLoginPlatformCode());
                    finalJson.put("topic", "jxzsRes");
                    finalJson.put("data", json.toJSONString());
                    String upSyncUrl = "http://kcapi.huijiaoyun.com/res-course/logMessage/saveKafka";
                    String jsonStr = com.alibaba.fastjson.JSONObject.toJSONString(finalJson);
                    LOGGER.info("参数：" + finalJson);
                    String textbookResponse = HttpClient.doJSONPostMethod(upSyncUrl, jsonStr);
                    System.out.println(textbookResponse);
                }
        }
    }

        //填充资源参数
        private Map<String, Object> getCommonParam(UserResRequest2 res) {
            Map<String, Object> properties = new HashMap<>();
            if (null != res) {
                properties.put("resId", res.getResId());
                properties.put("resTitle", res.getTitle());
                properties.put("periodId", res.getPeriodId());
                properties.put("periodName", res.getPeriodName());
                properties.put("subjectId", res.getSubjectId());
                properties.put("subjectName", res.getSubjectName());
                properties.put("gradeId", res.getGradeId());
                properties.put("textbookId", res.getTextbookId());
                properties.put("textbookName", res.getTextbookName());
                properties.put("chapterId", res.getChapterId());
                properties.put("resProvider", "");
                properties.put("resSize", res.getFileSize());
                properties.put("resContents", res.getTitle());
                properties.put("resStore", "0");
                properties.put("jxzsResType", res.getJxzsResType());
                properties.put("sourceResId", res.getSourceResId());


                properties.put("platform_code", res.getLoginPlatformCode());
                properties.put("org_id", res.getOrgId());
                properties.put("org_name", res.getOrgName());
            }

            properties.put("$time", new Date());
            return properties;
        }


    private void pushData(String eventName, String userId, Map<String, Object> data) throws Exception {
        SensorsAnalytics sa = SensorsAnalyticsUtils.getInstance();
        if (sa != null) {
            //null值 补上 ""
            for (String key : data.keySet()) {
                data.putIfAbsent(key, "");
            }
            if (org.apache.commons.lang3.StringUtils.isNotBlank(userId)) {
                sa.track(userId, true, eventName, data);
            } else {
                sa.track(IpUtils.getRealIp(), false, eventName, data);
            }
            LOGGER.warn("推送成功，eventName ：{}，data：{}", eventName, data);
        } else {
            LOGGER.error("神策埋点为空！");
        }
    }
}
